Thực đơn
Mẫu hợp tử Ví dụVí dụ sau minh hoạ ví dụ nêu ở trên với kết quả là:
(Europe: (England: London) (France: Paris))
import java.util.*;interface Component { public String defaultMethod(); public ArrayList<Component> getChildren(); public boolean addComponent(Component c); public boolean removeComponent(Component c);}class Composite implements Component { private String id; private ArrayList<Component> components = new ArrayList<Component>(); public Composite(String identification) { id = identification; } public String defaultMethod() { String s = " (" + id + ":"; for (Component child: getChildren()) s += " " + child.defaultMethod(); return s + ") "; } public ArrayList<Component> getChildren() { return components; } public boolean addComponent(Component c) { return components.add(c); } public boolean removeComponent(Component c) { return components.remove(c); }} class Leaf implements Component { private String id; public Leaf(String identification) { id = identification; } public String defaultMethod() { return id; } public ArrayList<Component> getChildren() { return null; } public boolean addComponent(Component c) { return false; } public boolean removeComponent(Component c) { return false; }}class CompositePattern { public static void main(String[] args) { Composite england = new Composite("England"); Leaf york = new Leaf("York"); Leaf london = new Leaf("London"); england.addComponent(york); england.addComponent(london); england.removeComponent(york); Composite france = new Composite("France"); france.addComponent(new Leaf("Paris")); Composite europe = new Composite("Europe"); europe.addComponent(england); europe.addComponent(france); System.out.println(europe.defaultMethod()); }}
Thực đơn
Mẫu hợp tử Ví dụLiên quan
Mẫu Mẫu (đơn vị đo) Mẫu Anh Mẫu hình Mẫu thiết kế phần mềm Mẫu Sơn Mẫu (dạng thức) Mẫu Bạch Kê Mẫu đơn đình Mẫu thầnTài liệu tham khảo
WikiPedia: Mẫu hợp tử https://archive.org/details/designpatternsel00gamm...